# -*- coding: utf-8 -*-
import hashlib

from flask import Blueprint
from flask import request
from public.log_util import logger
from model.User_model import UserModel, UserSchema
from public.response import Response
from service.user_service import UserService

user_bp = Blueprint('user_view', __name__, url_prefix='/user')


# 查看一個用户
@user_bp.route('/userid', endpoint='one', methods=["GET"])
def user():
    id = request.json['id']
    us = UserSchema()
    data = UserService.get(id)
    ret = us.dumps(data)
    return ret


# 显示所有用户
@user_bp.route('/userall', endpoint='all', methods=["GET"])
def user_all():
    us = UserSchema()
    user_list = UserService.get_all()
    list_data = us.dumps(user_list, many=True)
    return list_data


# 用户登录
@user_bp.route('/login', endpoint='login', methods=["POST"])
def user_login():
    req_data = request.json
    username = req_data.get("username")
    password = req_data["password"]
    name = UserService.get_name(username)
    logger.info(f"name: {name}")
    if not name:
        return Response.success(data=username, msg=f'用户名不存在!')
    pwd = hashlib.sha1(password.encode("utf-8")).hexdigest()
    if pwd != name.password:
        return Response.success(data=username, msg=f'用户名或密码不正确!')
    else:
        return Response.success(data=username, msg=f'登录成功!')


# 用户注册
@user_bp.route('/register', endpoint='register', methods=['POST'])
def user_register():
    req_data = request.json
    username = req_data.get("username")
    password = req_data["password"]

    name = UserService.get_name(username)
    if name:
        return Response.success(data=username, msg=f'用户名存在,请重新输入!')

    pwd = hashlib.sha1(password.encode("utf-8")).hexdigest()
    req_data["password"] = pwd

    body = UserModel(**req_data)
    res = UserService.save(body)

    if res != None:
        return Response.success(data=username, msg='注册成功!')
    else:
        return Response.error(msg='注册失败!')
